/*
 * CategoryManagement.fx
 * Author: Yu Min-ting
 * Created on 2009-7-17, 12:08:31
 */

package com.sjtu.fx.admin;

import javafx.scene.*;
import javax.swing.*;
import javax.swing.tree.*;
import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;
import org.json.JSONArray;

import javax.swing.tree.*;

import java.lang.String;
import java.lang.System;
import javafx.scene.paint.Color;
import javafx.scene.layout.*;

import javafx.ext.swing.SwingComponent;
import javafx.scene.control.TextBox;

import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.control.Button;

import javafx.stage.Alert;

import java.util.Hashtable;
import com.sjtu.fx.tools.Panel;

import com.sjtu.fx.tools.UIAlert;

public class CategoryManagement extends CustomNode {
     var panel:Panel;
     var category:JSONArray;
     var subcates:JSONArray;
     var treeModel:DefaultTreeModel;
     var tree:JTree = new JTree();
     var scrollPane:JScrollPane;
     var selectedValue:Object;
     var newCategoryParent:String;
     public var update:UpdateNewBooks;
     var hash:Hashtable;
     var root:DefaultMutableTreeNode;

     var categoryText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "Book Category :"
    };
     var categoryPath = TextBox {
             promptText: "Please choose book's category"
             columns: 20
             selectOnFocus: true
             editable:false
         }
      var alert = UIAlert {
         translateX:75
         translateY:200
         title:"ERROR"
         content:"Please input entire information"
         width:280
         height:120
         visible:false
         opacity:0.9
     }
     var addCategory = Button {
             text: "Add New Category"
             action: function() {
                if(selectedValue == null){
                    alert.content = "Please choose the parent category first!";
                    alert.visible = true;
                    //Alert.inform("Error","Please choose the parent category first!")
                }else{
                    nameText.visible = true;
                    nameTextBox.visible = true;
                    confirm.visible = true;
                    newCategoryParent = selectedValue.toString();
                }
             }
         }
     var addExplain = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "  Add a New Category Steps:   \n"  
        "1.Click the parent Category\n "
        "2.Press 'Add New Category' button\n"
        "3.Input the category name \n "  
        "4.Press the 'Confirm' button"
       
    };
    var nameText = Text{
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content:"New Category Name"
        visible:false
    };
    var nameTextBox = TextBox {
            promptText:"Input category name here"
            columns: 20
            selectOnFocus: true
            visible: false
        }
    var confirm = Button {
            text: "Confirm"
            visible:false
            action: function() {
                if(nameTextBox.text == ""){
                     alert.content = "Please input the category name!";
                     alert.visible = true;
                     //Alert.inform("Error","Please input the category name!")
                }else{
                var parent:DefaultMutableTreeNode = hash.get(newCategoryParent) as DefaultMutableTreeNode;
                var newCategory:DefaultMutableTreeNode = new DefaultMutableTreeNode(nameTextBox.text);
                var index:Integer = treeModel.getChildCount(parent);
                treeModel.insertNodeInto(newCategory, parent,index);
                hash.put(nameTextBox.text,newCategory);
                System.out.println("nameTextBox{nameTextBox.text}");
                System.out.println("newCategoryParent{newCategoryParent}");
                setNewCategory(nameTextBox.text,newCategoryParent);
                //to store the son(nameTextBox.text) into parent(newCategroyParent) into database
                }
            }
        }
    var OK = Button {
            text: "BACK"
            translateX:180 translateY:450
            action: function() {
                if(categoryPath.text == ""){
                    alert.content = "Please choose book's category!";
                    alert.visible = true;
                    //Alert.inform("Error","Please choose book's category!")
                }else{
                    update.categoryTextBox.text = categoryPath.text;
                    visible = false;
                }
            }
        }

    override protected function create() : Node {
       root = new DefaultMutableTreeNode("Category");
       treeModel = new DefaultTreeModel(root);
       hash = new Hashtable(10,0.8);
       tree = new JTree(treeModel);
       scrollPane = new JScrollPane(tree);
       hash.put("Category", root);
       getMainCategory();
//       createTree();
        
 /*       Group{
            content:[
              //  myTree,
                SwingComponent.wrap(scrollPane)
            ]
        }
*/        Group{
            content:[
                 panel = Panel {
                    width:    430
                    height:   550
                    title:    "Category Management"
                    translateX: 0
                    translateY: 0
                },
                 HBox{
                    spacing:45
                    translateX:50 translateY: 70
                    content:[  SwingComponent.wrap({scrollPane}),
                    VBox{
                        spacing:20
                        translateX:0 translateY:10
                        content:[
                            VBox{
                                spacing:15
                                content:[categoryText, categoryPath]
                            },
                            VBox{
                                spacing:15
                                translateY:10
                                content:[addExplain,addCategory,nameText,nameTextBox,confirm ]
                            }
                            
                        ]
                    }    ]
                },
                OK,alert
            ]
        }
}

function getMainCategory(){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/MainCategory"
       onOutput: function(os:OutputStream) {
             try {
                os.write("1".getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
        try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
       //         System.out.println(result);
                json = new JSONObject(result);
                category = json.getJSONArray("mainCategory");
            } finally {
                createTree();
                is.close();
            }
        }
    }.start();
}

function createTree(){
       //        var root:DefaultMutableTreeNode = new DefaultMutableTreeNode("Category");
       //        treeModel = new DefaultTreeModel(root);
       //         hash = new Hashtable(10,0.8);
                var i:Integer = 0;
                var contentsOne:DefaultMutableTreeNode[];
                System.out.println(category);
                while(i<category.length())
                {
                   contentsOne[i]  = new DefaultMutableTreeNode(category.get(i).toString());
                    treeModel.insertNodeInto(contentsOne[i], root, i);
                    hash.put(category.get(i).toString(),contentsOne[i]);
                    i++;
                }
      //          tree = new JTree(treeModel);
     //           System.out.println(treeModel.getChild(treeModel.getRoot(),1));
     //           System.out.println(tree.getWidth());
                tree.setAutoscrolls(true);
     //           scrollPane = new JScrollPane(tree);
     //           scrollPane.add(tree);
     //           scrollPane.add(new JButton("aaaa"));
     //           System.out.println(tree.getWidth());
                scrollPane.repaint();
                var  mouseListener = java.awt.event.MouseAdapter {
                    override function mousePressed(e: java.awt.event.MouseEvent) {
                        var selRow = tree.getRowForLocation(e.getX(), e.getY());
                        var selPath = tree.getPathForLocation(e.getX(), e.getY());
                        var lastPath = selPath.getPathComponent(selPath.getPathCount() - 1);
                        var obj = (lastPath as DefaultMutableTreeNode).getUserObject();
                        if(selRow != - 1) {
                            if(e.getClickCount() == 1) {
                                selectedValue = obj;
                                System.out.println(selectedValue);
                                categoryPath.text = selectedValue.toString();
                            }
                            else if(e.getClickCount() == 2) {
                                System.out.println("selectedValue:{selectedValue.toString()}");
                                if(selectedValue.equals("Category")){}
                                else{
                                AddSubCategory(selectedValue.toString());
                                }
                            }
                        }
                      tree.repaint();
                    }
                };
                tree.addMouseListener(mouseListener);
                var renderer=   new DefaultTreeCellRenderer();
                renderer.setClosedIcon(null);
                renderer.setOpenIcon(null);
                renderer.setLeafIcon(null);
                tree.setCellRenderer(renderer);
}
function AddSubCategory(selectValue:String){
    if(hash.get(selectValue)!=null)
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/SubCategory"
       onOutput: function(os:OutputStream) {
             try {
                var json:JSONObject = JSONObject{};
                json.put("fatherCategory",selectValue);
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
        try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                System.out.println("******{result}******");
                json = new JSONObject(result);
                subcates = json.getJSONArray("subcates");
                var i:Integer;
                while(i<subcates.length())
                {
                    var sonNode:DefaultMutableTreeNode = new DefaultMutableTreeNode(subcates.get(i).toString());
                    System.out.println("hash.get(selectValue):{subcates.get(i)}");
                    treeModel.insertNodeInto(sonNode, hash.get(selectValue) as DefaultMutableTreeNode, i);
                    hash.put(subcates.get(i).toString(),sonNode);
                    i++;
                }
            } finally {
                scrollPane.repaint();
                is.close();
            }
        }
    }.start();
}
function setNewCategory(sonContent:String,parentContent:String){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/AddCategory"
       onOutput: function(os:OutputStream) {
             try {
                var json:JSONObject = JSONObject{};
                json.put("sonContent",sonContent);
                json.put("parentContent", parentContent);
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
        try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                System.out.println("******{result}******");
            } finally {
                scrollPane.repaint();
                is.close();
            }
        }
    }.start();
}

}
